package ps3838

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"

	"lottery/models"
	"lottery/utils"

	"github.com/robertkrimen/otto"
)

var gameDataJs = `
events = %s
events = events["l"][0][2]

games = [];
gameDatas = [];
for (var eventIndex in events) {
	league = events[eventIndex]
	if (league[1].indexOf("角球") != -1) {
		continue;
	}

	leagueGames = league[2];
	for (var gameIndex in leagueGames) {
		game = leagueGames[gameIndex];
		games.push({
			"leagueId": league[0],
			"leagueName": league[1],
			"gameId": game[0],
			"hName": game[1],
			"aName": game[2],
			"playTime": game[4]
		})

		gameRates = game[8]
		if ( gameRates === null ) {
			continue;
		}

		if (gameRates["0"] != null) {
			// 全场
			upderHandicapRates = gameRates["0"]
			for (var rateIndex in upderHandicapRates[0]) {
			 	// 全场让球
			 	rateItem = upderHandicapRates[0][rateIndex]
			 	gameDatas.push({
			 		"handicapId": rateItem[7], // 盘口ID
			 		"handicap": rateItem[0], // 盘口大小
			 		"handicapType": 1, // 全场让球
			 		"gameId": game[0], // 比赛ID
			 		"hScore": game[9][0], // 主场比分
			 		"aScore": game[9][1], // 客场比分
			 		"hRate": Number(rateItem[3]), // 主场赔率
			 		"aRate": Number(rateItem[4]) // 客场赔率
					"extData":rateItem[8]      //特殊数据，，点水需要的多盘口区分
			 	})
			}

			for (var rateIndex in upderHandicapRates[1]) {
			 	// 全场大小球
			 	rateItem = upderHandicapRates[1][rateIndex]
			 	gameDatas.push({
			 		"handicapId": rateItem[4], // 盘口ID
			 		"handicap": rateItem[1], // 盘口大小
			 		"handicapType": 2, // 全场大小球
			 		"gameId": game[0], // 比赛ID
			 		"hScore": game[9][0], // 主场比分
			 		"aScore": game[9][1], // 客场比分
			 		"hRate": Number(rateItem[2]), // 主场赔率
			 		"hIndicator": 1, // 大球
			 		"aRate": Number(rateItem[3]), // 客场赔率
			 		"aIndicator": 2 // 小球
					"extData":rateItem[5]        //特殊数据，，点水需要的多盘口区分
			 	})
			}
		}

		if (gameRates["1"] != null) {
			// 半场
			downHandicapRates = gameRates["1"]
			for (var rateIndex in downHandicapRates[0]) {
			 	// 半场让球
			 	rateItem = downHandicapRates[0][rateIndex]
			 	gameDatas.push({
			 		"handicapId": rateItem[7], // 盘口ID
			 		"handicap": rateItem[0], // 盘口大小
			 		"handicapType": 3, // 半场让球
			 		"gameId": game[0], // 比赛ID
			 		"hScore": game[9][0], // 主场比分
			 		"aScore": game[9][1], // 客场比分
			 		"hRate": Number(rateItem[3]), // 主场赔率
			 		"aRate": Number(rateItem[4]) // 客场赔率
					"extData":rateItem[8]      //特殊数据，，点水需要的多盘口区分
			 	})
			}

			for (var rateIndex in downHandicapRates[1]) {
			 	// 半场大小球
			 	rateItem = downHandicapRates[1][rateIndex]
			 	gameDatas.push({
			 		"handicapId": rateItem[4], // 盘口ID
			 		"handicap": rateItem[1], // 盘口大小
			 		"handicapType": 4, // 半场大小球
			 		"gameId": game[0], // 比赛ID
			 		"hScore": game[9][0], // 主场比分
			 		"aScore": game[9][1], // 客场比分
			 		"hRate": Number(rateItem[2]), // 主场赔率
			 		"hIndicator": 1, // 大球
			 		"aRate": Number(rateItem[3]), // 客场赔率
			 		"aIndicator": 2 // 小球
					"extData":rateItem[5]        //特殊数据，，点水需要的多盘口区分
			 	})
			}
		}
	}
}
gameStr = JSON.stringify(games);
gameDataStr = JSON.stringify(gameDatas);
`

func (p *Ps3838) getGameData() (games []*models.Game, gameDatas []*models.GameData, err error) {
	reqUrl := fmt.Sprintf("http://www.ps3838.com/sports-service/sv/odds/events?mk=2&sp=29&ot=4&btg=1&o=1&lg&ev&l=3&more=false&c=CN&tm=0&g=QQ%%3D%%3D&pa=0&locale=zh_CN")
	req, err := http.NewRequest("GET", reqUrl, nil)
	if err != nil {
		return
	}

	req.Header.Set("User-Agent", p.userAgent)
	req.Header.Set("Referer", "http://www.ps3838.com/zh-cn/sports")
	req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
	req.Header.Set("X-Requested-With", "XMLHttpRequest")

	//fmt.Println("cookies:",p.jar.Cookies(req.URL))
	//req.Header = p.getDefaultHeader()
	resp, err := p.client.Do(req)
	if err != nil {
		return
	}

	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	//fmt.Println("sss", string(data))
	jsBody := fmt.Sprintf(gameDataJs, string(data))
	vm, _, err := otto.Run(jsBody)
	if err != nil {
		return
	}

	now := utils.CurrentMills()
	gameValue, err := vm.Get("gameStr")
	if err != nil {
		return
	}

	pgames := make([]*PGame, 0, 10)
	if err = json.Unmarshal([]byte(gameValue.String()), &pgames); err != nil {
		return
	}

	games = make([]*models.Game, 0, len(pgames))
	for _, pgame := range pgames {
		game := &models.Game{
			PlatformId:     p.Platform(),
			PlatformGameId: strconv.FormatInt(pgame.GameId, 10),
			LeagueGameId:   strconv.FormatInt(pgame.LeagueId, 10),
			LeagueGameName: pgame.LeagueName,
			HName:          pgame.HName,
			AName:          pgame.AName,
			PlayTime:     	strconv.FormatInt(pgame.PlayTime,10),
			StartTime:      pgame.PlayTime,
			CreateTime:     now,
		}
		games = append(games, game)
	}

	gamedataValue, err := vm.Get("gameDataStr")
	if err != nil {
		return
	}

	pgameDatas := make([]*PGameData, 0, 100)
	if err = json.Unmarshal([]byte(gamedataValue.String()), &pgameDatas); err != nil {
		return
	}

	gameDatas = make([]*models.GameData, 0, len(pgameDatas))
	for _, pgamedata := range pgameDatas {

		//获取game
		game :=&models.Game{}
		for _,game_tmp :=range games{
			if(game_tmp.PlatformGameId==strconv.FormatInt(pgamedata.GameId, 10)){
				game =game_tmp
				break
			}
		}

		gameData := &models.GameData{
			PlatformId:     p.Platform(),
			PlatformGameId: strconv.FormatInt(pgamedata.GameId, 10),
			HandicapId:     strconv.FormatInt(pgamedata.HandicapId, 10),
			Handicap:       pgamedata.Handicap,
			HandicapType:   pgamedata.HandicapType,
			HRate:          pgamedata.HRate,
			HIndicator:     pgamedata.HIndicator,
			ARate:          pgamedata.ARate,
			AIndicator:     pgamedata.AIndicator,
			HScore:         pgamedata.HScore,
			AScore:         pgamedata.AScore,
			AgentId:        p.agentInfo.Id,
			ExtData:        strconv.Itoa(pgamedata.ExtData),
			Game:			game,
			CreateTime:     now,
		}
		gameDatas = append(gameDatas, gameData)
	}
	return
}
